package com.asmember;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author Grzegorz Matyszczak<BR>
 *
 */
public class RIPERequestHelper {

	private static final String SERVER_URL = "http://apps.db.ripe.net/whois";
	
	public static String makeRequest(String asNumber)  {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String result = null;
		
        try {
            HttpGet httpget = new HttpGet(SERVER_URL+"/grs-search?source=ripe-grs&source=afrinic-grs&source=apnic-grs&source=arin-grs&source=lacnic-grs&source=radb-grs&query-string="+asNumber+"&type-filter=route&inverse-attribute=origin");
            httpget.setHeader("Accept", "application/json");
            

            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

                public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            
            result = httpclient.execute(httpget, responseHandler);
            
        } catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
            try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        
		return result;
	}
	
}
